package org.minhnvt1.android.moviesearch.services;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.minhnvt1.android.moviesearch.handlers.MovieHandler;
import org.minhnvt1.android.moviesearch.handlers.PersonHandler;
import org.minhnvt1.android.moviesearch.model.Movie;
import org.minhnvt1.android.moviesearch.model.Person;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class XmlParser {
	private XMLReader initializeReader() throws ParserConfigurationException, SAXException{
		SAXParserFactory factory = SAXParserFactory.newInstance();
		//create a parser
		SAXParser parser = factory.newSAXParser();
		//create the reader(scanner)
		XMLReader xmlreader = parser.getXMLReader();
		return xmlreader;
	}
	//Person
	public ArrayList<Person> parserPeopleResponse(String xml){
		try{
			XMLReader xmlreader = initializeReader();
			PersonHandler personHandler = new PersonHandler();
			
			//assign our handler
			xmlreader.setContentHandler(personHandler);
			// perform the synchronous parse
			xmlreader.parse(new InputSource(new StringReader(xml)));
			
			return personHandler.retrievePersonList();
			
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	// Movie
	public ArrayList<Movie> parserMovieResponse(String xml){
		try{
			XMLReader xmlreader = initializeReader();
			MovieHandler movieHandler = new MovieHandler();
			
			xmlreader.setContentHandler(movieHandler);
			xmlreader.parse(new InputSource(new StringReader(xml)));
			
			return movieHandler.retrieveMovieList();
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
